package atech.ace.mapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import atech.ace.mapping.persistence.entities.Company;
import atech.ace.mapping.persistence.entities.HumanResource;
import atech.ace.mapping.persistence.entities.Project;

/**
 * Servlet implementation class CreateProject
 */
@WebServlet("/CreateProject")
public class CreateProject extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@PersistenceContext(name = "jdbc/ACE_ProjectMapping")
	EntityManager em;

	@Resource
	UserTransaction utx;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String longitudeString = request.getParameter("lng");
		String latitudeString = request.getParameter("lat");
		String location = request.getParameter("location");
		Project project = new Project();
		project.setProjectName(name);
		project.setLocation(location);
		project.setLatitude(Double.parseDouble(latitudeString));
		project.setLongitude(Double.parseDouble(longitudeString));

		try {
			utx.begin();
			Company company = em.find(Company.class, request.getParameter("company"));
			String[] resources = request.getParameterValues("humanResources");
			project.setCompany(company);
			ArrayList<HumanResource> realResources = new ArrayList<HumanResource>();
			for (String resourceID : resources) {
				HumanResource resource = em.find(HumanResource.class, resourceID);
				realResources.add(resource);
			}
			project.setHumanResources(realResources);
			String[] errs = Validation.validateProject(project);
			if (errs.length > 0) {
				utx.rollback();
				request.setAttribute("errs", errs);
				request.getRequestDispatcher("Create").forward(request, response);
			} else {
				project.setHumanResources(null);
				em.persist(project);
				utx.commit();
				utx.begin();
				Query query = em.createQuery("select p from Project p where p.projectName = :name");
				query.setParameter("name", name);
				Project projectWithID = (Project) query.getResultList().get(0);
				realResources = new ArrayList<HumanResource>();
				for (String resourceID : resources) {
					HumanResource resource = em.find(HumanResource.class, resourceID);
					List<Project> resourceProjects = resource.getProjects();
					resourceProjects.add(projectWithID);
					em.merge(resource);
				}
				projectWithID.setHumanResources(realResources);
				em.merge(projectWithID);
			}
			utx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				utx.rollback();
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (SystemException e1) {
				e1.printStackTrace();
			}
		}

		response.sendRedirect("Create");
	}

}
